package org.elastic.compreplatform.conf.core;

import org.elastic.compreplatform.conf.core.core.ConfLocalCacheConf;
import org.elastic.compreplatform.conf.core.core.ConfPropConf;
import org.elastic.compreplatform.conf.core.core.ConfZkConf;
import org.elastic.compreplatform.conf.core.exception.ZookConfException;
import org.elastic.compreplatform.conf.core.listener.ConfListener;
import org.elastic.compreplatform.conf.core.listener.ConfListenerFactory;

/**
 * ClassName: ZookConfClient 
 * @Description: zookeeper client
 * @author JornTang
 * @date 2018年3月4日
 */
public class ZookConfClient {

	/**
	 * get conf
	 *
	 * @param key
	 * @param defaultVal
	 * @return
	 */
	public static String get(String key, String defaultVal) {
		// level 1: prop conf
		String propConf = ConfPropConf.get(key);
		if (propConf != null) {
			return propConf;
		}

		// level 2: local cache
		ConfLocalCacheConf.CacheNode cacheNode = ConfLocalCacheConf.get(key);
		if (cacheNode != null) {
			return cacheNode.getValue();
		}

		// level 3	(get-and-watch, add-local-cache)
		String zkData = ConfZkConf.get(key);
		ConfLocalCacheConf.set(key, zkData, "SET");		// support cache null value
		if (zkData != null) {
			return zkData;
		}

		return defaultVal;
	}

	/**
	 * get conf (string)
	 *
	 * @param key
	 * @return
	 */
	public static String get(String key) {
		return get(key, null);
	}

	/**
	 * get conf (int)
	 *
	 * @param key
	 * @return
	 */
	public static int getInt(String key) {
		String value = get(key, null);
		if (value == null) {
			throw new ZookConfException("config key [" + key + "] does not exist");
		}
		return Integer.valueOf(value);
	}

	/**
	 * get conf (long)
	 *
	 * @param key
	 * @return
	 */
	public static long getLong(String key) {
		String value = get(key, null);
		if (value == null) {
			throw new ZookConfException("config key [" + key + "] does not exist");
		}
		return Long.valueOf(value);
	}

	/**
	 * get conf (boolean)
	 *
	 * @param key
	 * @return
	 */
	public static boolean getBoolean(String key) {
		String value = get(key, null);
		if (value == null) {
			throw new ZookConfException("config key [" + key + "] does not exist");
		}
		return Boolean.valueOf(value);
	}

	/**
	 * add listener with xxl conf change
	 *
	 * @param key
	 * @param xxlConfListener
	 * @return
	 */
	public static boolean addListener(String key, ConfListener xxlConfListener){
		return ConfListenerFactory.addListener(key, xxlConfListener);
	}
	
}
